package com.theaf.core.shiro;

import com.theaf.core.api.model.UserInfo;
import com.theaf.core.cache.ThreadLocalHelper;
import com.theaf.core.utils.LoginUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;


/**
 * 验证用户登录
 * @author Administrator
 */
@Component("userRealm")
public class UserRealm extends AuthorizingRealm {
	public static String SHIRO_SESSION_PREFIX = "5g-shiro-session:";
	public static String NAME = "UserRealm";
	public static String INLINE_INFO = "INLINE_INFO";//系统地址


	public UserRealm() {
		setName(NAME);
		setCredentialsMatcher(new CredentialsMatcher());
	}


	/**
	 * 生成缓存KEY
	 * @param token
	 * @return
	 */
	@Override
	protected Object getAuthenticationCacheKey(AuthenticationToken token) {
		return token != null ? token.getPrincipal() : null;
	}


	@Override
	/**
	 * 登录验证
	 * @param token
	 * @return
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upt = (UsernamePasswordToken) token;
		String userName = upt.getUsername();
		UserInfo user= (UserInfo) ThreadLocalHelper.get(INLINE_INFO);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, null, getName());
		return info;
	}

	/**
	 * 密码校验
	 */
	private class CredentialsMatcher extends SimpleCredentialsMatcher {
		@Override
		public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
			/*UsernamePasswordToken utoken=(UsernamePasswordToken) token;
			//获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
			String inPassword = new String(utoken.getPassword());
			//获得数据库中的密码
			String dbPassword=(String) info.getCredentials();
			UserInfo userInfo = (UserInfo)info.getPrincipals().fromRealm(getName()).iterator().next();
			String salt = (userInfo).getSalt();
			userInfo.setPassword(null);
			userInfo.setSalt(null);
			//进行密码的比对
			return this.equals(PasswordUtils.encodePassword(inPassword,salt), dbPassword);*/
			return true;
		}
	}

	// 授权 权限资源角色
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserInfo user=(UserInfo) principals.fromRealm(getName()).iterator().next();//获取session中的用户
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		info.addStringPermissions(LoginUtils.getFunAathUrl());//将权限放入shiro中.
		return info;
	}
}